<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use common\components\Upload;
use common\models\business\BusinessContractStatements;
use common\models\business\BusinessSaleorder;
use Yii;
use common\models\business\BusinessContractPurchase;
use backend\modules\business\models\BusinessContractPurchaseSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\business\BusinessPig;
use yii\web\Response;

/**
 * ContractPurchaseController implements the CRUD actions for BusinessContractPurchase model.
 */
class ContractPurchaseController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessContractPurchase models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessContractPurchaseSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessContractPurchase model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessContractPurchase model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessContractPurchase();

        if ($model->load(Yii::$app->request->post())) {

            $postdata = Yii::$app->request->post();

            if(!isset($postdata['cost']) || !isset($postdata['id'])){
                return $this->dialog('购进的仔猪不能为空');
            }


            if(false !== $photo = Upload::upload($model,'file')){
                $model->setAttribute('file',$photo);
            }
            $model->price =array_sum($postdata['cost']);
            $model->num =count(array_filter($postdata['id']));
            $model->inputuser = Yii::$app->user->identity->username;
            if (!$model->save()) {
                return $this->dialog($this->checkError($model));
            }

            //取出删除的id
            $hasids = (new Query())->select('id')->from(BusinessPig::tableName())
                ->where('contract_purid=:id',[':id'=>$model->id])
                ->all();
            $idarr = ArrayHelper::getColumn($hasids,'id');
            $delids =  array_diff($idarr,$postdata['id']);

            foreach ($postdata['id'] as $key => $row) {
                $cost = $postdata['cost'][$key]?$postdata['cost'][$key]:0;
                Yii::$app->db->createCommand()->update(BusinessPig::tableName(), ['contract_purid' => $model->id, 'cost' => $cost], 'id=:id', [':id' => $row])
                    ->execute();
            }

            //删除
            foreach ($delids as $key => $row){
                Yii::$app->db->createCommand()->update(BusinessPig::tableName(), ['contract_purid' => 0, 'cost' => 0], 'id=:id', [':id' => $row])
                    ->execute();
            }

            return $this->redirect(['view', 'id' => $model->id]);

        } else {
            $model->createtime = empty($model->createtime)?date("Y-m-d"):date("Y-m-d",$model->createtime);
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing BusinessContractPurchase model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {

            $postdata = Yii::$app->request->post();
            if(!isset($postdata['cost']) || !isset($postdata['id'])){
                return $this->dialog('购进的仔猪不能为空');
            }


            if(false !== $photo = Upload::upload($model,'file')){
                $model->setAttribute('file',$photo);
            }

            $model->price =array_sum($postdata['cost']);
            $model->num =count(array_filter($postdata['id']));
            if (!$model->save()) {
                return $this->dialog($this->checkError($model));
            }

            //取出删除的id
            $hasids = (new Query())->select('id')->from(BusinessPig::tableName())
                ->where('contract_purid=:id',[':id'=>$model->id])
                ->all();
            $idarr = ArrayHelper::getColumn($hasids,'id');
            $delids =  array_diff($idarr,$postdata['id']);

            foreach ($postdata['id'] as $key => $row) {
                $cost = $postdata['cost'][$key]?$postdata['cost'][$key]:0;
                Yii::$app->db->createCommand()->update(BusinessPig::tableName(), ['contract_purid' => $model->id, 'cost' => $cost], 'id=:id', [':id' => $row])
                    ->execute();
            }

            //删除
            foreach ($delids as $key => $row){
                Yii::$app->db->createCommand()->update(BusinessPig::tableName(), ['contract_purid' => 0, 'cost' => 0], 'id=:id', [':id' => $row])
                    ->execute();
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $model->createtime = empty($model->createtime)?date("Y-m-d"):date("Y-m-d",$model->createtime);
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing BusinessContractPurchase model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        BusinessPig::updateAll(['contract_purid'=>0],'contract_purid=:id',[':id'=>$id]);
        $this->findModel($id)->delete();


        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessContractPurchase model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessContractPurchase the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessContractPurchase::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     * @param $id
     * 审核
     */
    public function actionAgree($id)
    {
        $data = [
            'agreeuser' => Yii::$app->user->identity->username,
            'agreetime' => time(),
            'status' => BusinessContractPurchase::STATUS_AGREE
        ];
        $res = Yii::$app->db->createCommand()->update(BusinessContractPurchase::tableName(),$data,'id=:id',[':id'=>$id])
            ->execute();
        return $this->dialog('审核通过');
    }

    /**
     * Creates a new BusinessContractStatements model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreateStatement()
    {
        $model = new BusinessContractStatements();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->renderPartial('createstatement', [
                'model' => $model,
            ]);
        }
    }


    /**
     * 搜索购进的仔猪
     */
    public function actionSearchPigs()
    {
        $this->layout = false;

        $hasid = Yii::$app->request->post('selid')?Yii::$app->request->post('selid'):[];
        $query = (new Query())->select('pig.no,pig.id')->from(['pig'=>BusinessPig::tableName()])
            ->where('contract_purid=0');

        //去掉前台已经选择的仔猪
        if(!empty($hasid)){
            $pigs = $query->andWhere(['not in','pig.id',$hasid])->all();
        }else{
            $pigs = $query->all();
        }

        if(empty($pigs)){
            return '没有可以放入购进单的仔猪';
        }
        return $this->render('_pigs',[
            'pigs' => $pigs
        ]);

    }


    //获取选择的仔猪的信息
    public function actionGetInfo()
    {
        $data = Yii::$app->request->post('data');
        if(empty($data)){
            return ['data'=>'参数错误'];
        }

        Yii::$app->response->format = Response::FORMAT_JSON;
        $pigs = (new  Query())->select('pig.id,pig.no')
            ->from(['pig'=>BusinessPig::tableName()])
            ->where(['id'=>$data])
            ->all();
        return $pigs;
    }

}
